#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
using namespace std;

const int N = 1e6 + 10, INF = 0x3f3f3f3f;


void solve()
{
    int n, m;
    cin >> n >> m;
    vector<pair<int, int>> pos(n * m + 10);

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            int x;
            cin >> x;
            pos[x] = { i, j };
        }
    }

    auto check = [&](int mid)
        {
            vector<pair<int, int>> p;
            for (int i = 0; i < mid; i++) {
                p.push_back(pos[i]);
            }

            sort(p.begin(), p.end(), [](auto a, auto b)
                {
                    if (a.first != b.first) return a.first < b.first;
                    else return a.second < b.second;
                });

            int lx = 0, ly = 0;
            for (auto [x, y] : p) {
                if (x < lx || y < ly) return false;
                lx = x, ly = y;
            }
            return true;
        };

    int l = 1, r = n * m;
    while (l < r) {
        int mid = (l + r + 1) / 2;
        if (check(mid)) l = mid;
        else r = mid - 1;
    }
    cout << l << "\n";
}

signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
#define ONLINE_JUDGE
#ifndef ONLINE_JUDGE
    std::istringstream in(R"()");
    std::cin.rdbuf(in.rdbuf());
#endif
    int T = 1;
    cin >> T;
    for (int i = 1;i <= T;i++) {
        solve();
    }
}